package com.ramos.kuaixiao.db;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.util.Log;

import com.ramos.kuaixiao.entity.ProductType;

import java.util.ArrayList;
import java.util.List;

public class ProductTypeDB {
    private static String TAG = "ProductTypeDB";
    private static String TABLE_NAME = "ProductType";
    public static final String CREATE_TABLE_SQL;
    public static final String DROP_USERINFO;

    static {
        CREATE_TABLE_SQL = "CREATE TABLE " + TABLE_NAME + " (" + "did" + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"
                + "type_id" + " CHAR(30)," + "parent_type_id" + " CHAR(30)," + "name" + " CHAR(30),"
                + "comment" + " CHAR(30)," + "dealer_id" + " CHAR(30)," + "tree_level" + " INTEGER," + "modifyTime " + " Long);";
        DROP_USERINFO = "DROP TABLE IF EXISTS " + TABLE_NAME;
    }

    public int addAllProductType(List<ProductType> list) {
        SQLiteDatabase db = DBHelper.open();
        db.execSQL("DELETE FROM ProductType");
        String sql = "insert into ProductType(type_id,parent_type_id,name,comment,dealer_id,tree_level,modifyTime) values(?,?,?,?,?,?,?)";
        db.beginTransaction();
        Long a = System.currentTimeMillis();
        SQLiteStatement stmt = db.compileStatement(sql);
        for (int i = 0; i < list.size(); i++) {
            stmt.bindString(1, list.get(i).getTypeId() + "");
            stmt.bindString(2, list.get(i).getParentTypeId() + "");
            stmt.bindString(3, list.get(i).getName() + "");
            stmt.bindString(4, list.get(i).getComment() + "");
            stmt.bindString(5, list.get(i).getDealerId() + "");
            stmt.bindString(6, list.get(i).getTreeLevel() + "");
            stmt.bindString(7, list.get(i).getModifyTime() + "");
            stmt.execute();
            stmt.clearBindings();
        }
        db.setTransactionSuccessful();
        db.endTransaction();
        Long b = System.currentTimeMillis();
        Log.i(TAG, String.valueOf(b - a));

        return 0;
    }

    public int updateAllProductType(List<ProductType> productTypes) {
        SQLiteDatabase db = DBHelper.open();
        db.beginTransaction();
        Long a = System.currentTimeMillis();
        Log.d(TAG, "updateAllShops:" + productTypes.size());
        for (int i = 0; i < productTypes.size(); i++) {
            ProductType productType = productTypes.get(i);
            if (hasProductType(productType.getTypeId() + "")) {
                ContentValues cv = new ContentValues();
                cv.put("parent_type_id", productType.getParentTypeId() + "");
                cv.put("name", productType.getName() + "");
                cv.put("comment", productType.getComment() + "");
                cv.put("dealer_id", productType.getDealerId() + "");
                cv.put("tree_level", productType.getTreeLevel() + "");
                cv.put("modifyTime", productType.getModifyTime() + "");
                db.update("ProductType", cv, "type_id=?", new String[]{productType.getTypeId() + ""});
            } else {
                ContentValues cv = new ContentValues();
                cv.put("type_id", productType.getTypeId() + "");
                cv.put("parent_type_id", productType.getParentTypeId() + "");
                cv.put("name", productType.getName() + "");
                cv.put("comment", productType.getComment() + "");
                cv.put("dealer_id", productType.getDealerId() + "");
                cv.put("tree_level", productType.getTreeLevel() + "");
                cv.put("modifyTime", productType.getModifyTime() + "");
                db.insert("ProductType", null, cv); //如果有记录，则更新，并返回1，否则返回0
            }
            // 生成的sql是 INSERT INTRO OR REPLACE INTO 这样的 (如果存在就替换存在的字段值. 存在的判断标准是主键冲突, 这里的主键是userId). 下面会介绍这个地方的方法
            //db.insertWithOnConflict("StoreNum",null, cv, SQLiteDatabase.CONFLICT_REPLACE) ; //如果有记录，则更新，并返回1，否则返回0
        }
        db.setTransactionSuccessful();
        db.endTransaction();
        Long b = System.currentTimeMillis();
        Log.i(TAG, String.valueOf(b - a));
        return 0;
    }

    private boolean hasProductType(String s) {
        SQLiteDatabase db = DBHelper.open();
        Cursor cursor = db.rawQuery("select * from ProductType where type_id =?", new String[]{s});
        if (cursor.getCount() > 0) {
            cursor.close();
            Log.d(TAG, "hasProductType true");
            return true;
        } else {
            Log.d(TAG, "hasProductType false");
            cursor.close();
            return false;
        }
    }


    public List<ProductType> findAllProductType() {
        List<ProductType> list = new ArrayList<>();
        SQLiteDatabase db = DBHelper.open();
        Cursor cursor = db.rawQuery("select * from ProductType", new String[]{});
        Log.d(TAG, "cursor:" + cursor.getCount());
        for (int i = 0; i < cursor.getCount(); i++) {
            cursor.moveToNext();
            ProductType customer = new ProductType();
            customer.setTypeId(cursor.getString(1));
            customer.setComment(cursor.getString(4));
            Log.d(TAG, "setType_id:" + cursor.getString(1) + " " + cursor.getString(4));
            list.add(customer);
        }
        cursor.close();
        //db.close();
        Log.d(TAG, "findAllProductType:" + list.size());
        return list;
    }

    public long getMaxModifyTime() {
        long param = 0;
        SQLiteDatabase db = DBHelper.open();
        Cursor cursor = db.rawQuery("select max(modifyTime)from ProductType ", new String[]{});
        Log.d(TAG, "getMaxModifyTime:getCount" + cursor.getCount());
        if (cursor.moveToFirst()) {
            param = cursor.getLong(0);
        }
        cursor.close();
        Log.d(TAG, "getMaxModifyTime:param" + param);
        return param;
    }

    public void deleteAll() {
        SQLiteDatabase db = DBHelper.open();
        db.execSQL("DELETE FROM ProductType");
        Log.d(TAG, "deleteAllProductType ");
    }

    public boolean hasData() {
        SQLiteDatabase db = DBHelper.open();
        Cursor cursor = db.rawQuery("select count(*)from ProductType", null);
        cursor.moveToFirst();
        Long count = cursor.getLong(0);
        if (count > 0) {
            cursor.close();
            Log.d(TAG, "hasProductType true");
            return true;
        } else {
            Log.d(TAG, "hasProductType false");
            cursor.close();
            return false;
        }
    }
}
